import sys,os
sys.path.append(os.pardir)
from common.functions import *
from common.gradient import numerical_gradient


class TwoLayerNet:
    def __init__ (self, input_size, hidden_size, output_size, weight_init_std=0.01):
        # 初始化权重
        self.params = {}
        # 第一层的权重
        self.params['W1'] = weight_init_std * np.random.randn(input_size, hidden_size)
        # 第一层的偏置
        self.params['b1'] = np.zeros(hidden_size)
        # 第二层的权重
        self.params['W2'] = weight_init_std * np.random.randn(hidden_size, output_size)
        # 第二层的偏置
        self.params['b2'] = np.zeros(output_size)

    def predict(self, x):
        W1, W2 = self.params['W1'], self.params['W2']
        b1, b2 = self.params['b1'], self.params['b2']
        a1 = np.dot(x, W1)
        z1 = sigmoid(a1)
        a2 = np.dot(z1, W2)
        y = softmax(a2)
        return y

    # 损失函数
    # x:输入数据, t:监督数据
    def loss(self, x, t):
        y = self.predict(x)
        return cross_entropy_error(y, t)

    # 计算精度
    def accuracy(self, x, t):
        y = self.predict(x)
        y = np.argmax(y, axis=1)
        t = np.argmax(t, axis=1)
        accuracy = np.sum(y == t) / float(x.shape[0])
        return accuracy

    # 梯度
    # x:输入数据, t:监督数据
    def numerical_gradient(self, x, t):
        # loss_W 现在是一个函数，接受一个参数 WW，
        # 并返回调用 self.loss(x, t) 的结果。
        loss_W = lambda W: self.loss(x, t)
        grads = {}
        # 保存第一层权重的梯度
        grads['W1'] = numerical_gradient(loss_W, self.params['W1'])
        # 保存第一层偏置的梯度
        grads['b1'] = numerical_gradient(loss_W, self.params['b1'])
        # 保存第二层权重的梯度
        grads['W2'] = numerical_gradient(loss_W, self.params['W2'])
        # 保存第二层偏置的梯度
        grads["b2"] = numerical_gradient(loss_W, self.params["b2"])

        return grads

    def gradient(self, x, t):
        W1, W2 = self.params['W1'], self.params['W2']
        b1, b2 = self.params['b1'], self.params['b2']
        grads = {}

        batch_num = x.shape[0]

        # forward
        a1 = np.dot(x, W1) + b1
        z1 = sigmoid(a1)
        a2 = np.dot(z1, W2) + b2
        y = softmax(a2)

        # backward 后向传播
        dy = (y - t) / batch_num
        grads['W2'] = np.dot(z1.T, dy)
        grads['b2'] = np.sum(dy, axis=0)

        dz1 = np.dot(dy, W2.T)
        da1 = sigmoid_grad(a1) * dz1
        grads['W1'] = np.dot(x.T, da1)
        grads['b1'] = np.sum(da1, axis=0)

        return grads
